/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.pacs.controller.service;

import com.cxhd.pacs.model.FileSystem;
import com.cxhd.pacs.tools.DateUtil;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 *
 * @author 52461
 */
public class PacsService {

    public String saveDicom(String studyIuid, String fileName, Controller con) {
        String path = null;
        FileSystem bf = FileSystem.dao.getPathInfo();
        if (studyIuid != null) {
            try {
                int fileSystemId = 0;
                String dir = "";
                String baseDir = "";
                String type = "file";
                if (bf != null) {
                    baseDir = bf.get("base_path");
                    dir = bf.get("base_path");
                    fileSystemId = bf.getInt("pk");
                }
                String filePath = null;

                Record re = Db.findFirst("select * from pacs_study where study_iuid='" + studyIuid + "'");
                if (re != null && re.getStr("file_path") != null) {
                    filePath = re.getStr("file_path");

                }
                if (filePath == null) {
                    filePath = dir + "/" + DateUtil.getNumFolder() + studyIuid + "/";
                }
                File fs = new File(filePath);
                if (!fs.exists()) {
                    fs.mkdirs();
                }
                fs = new File(filePath + fileName + ".dcm");

                BufferedInputStream bis = null;
                try {
                    bis = new BufferedInputStream(con.getRequest().getInputStream());
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                BufferedOutputStream bos = null;

                bos = new BufferedOutputStream(new FileOutputStream(fs));

                byte[] b = new byte[1024 * 64];
                int len = 0;
                try {
                    while ((len = bis.read(b)) > 0) {
                        bos.write(b, 0, len);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(PacsService.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    bos.flush();
                } catch (IOException ex) {
                    Logger.getLogger(PacsService.class.getName()).log(Level.SEVERE, null, ex);
                }
                bos.close();

                path = fs.getAbsolutePath();

            } catch (Exception ex) {
                ex.printStackTrace();
                return null;
            }

        }
        return path;
    }

    public boolean checkFile(String studyIuid, String sopIuid) {

        Record re = Db.findFirst("select * from pacs_study where study_iuid='" + studyIuid + "'");

        if (re != null && re.getStr("file_path") != null) {

            if (new File(re.getStr("file_path") + sopIuid + ".dcm").exists()) {

                return false;
            }
        }
        return true;

    }

    public String saveInfo(Map<String, String> info, String hospitalCode) {
        String pat_pk = null;
        Record re = Db.findFirst("select * from pacs_pat where pat_id='" + info.get("pat_id") + "' and hospital_code='" + hospitalCode + "'");
        if (re != null) {
            pat_pk = re.get("pk") + "";
        } else {
            Record pat_info = new Record();
            pat_info.set("pat_id", info.get("pat_id"));
            pat_info.set("pat_name", info.get("pat_name"));
            pat_info.set("pat_birth", info.get("pat_birth"));
            pat_info.set("pat_sex", info.get("pat_sex"));
            pat_info.set("pat_age", info.get("pat_age"));
            pat_info.set("create_time", DateUtil.getDateEN());
            pat_info.set("pat_id", info.get("pat_id"));
            pat_info.set("hospital_code", hospitalCode);
            Db.save("pacs_pat", pat_info);
            re = Db.findFirst("select * from pacs_pat where pat_id='" + info.get("pat_id") + "' and hospital_code='" + hospitalCode + "'");
            pat_pk = re.get("pk") + "";
        }
        return pat_pk;

    }

    public String saveStudy(Map<String, String> info, String pat_pk, String hospitalCode) {
        String study_pk = null;
        Record re = Db.findFirst("select * from pacs_study where pat_id='" + info.get("pat_id") + "' and hospital_code='" + hospitalCode + "' and study_iuid='" + info.get("study_iuid") + "'");
        if (re != null) {
            study_pk = re.get("pk") + "";
            Db.update("update pacs_study set file_count=file_count+1 where pk=" + re.get("pk"));
        } else {
            Record study_info = new Record();
            study_info.set("pat_pk", pat_pk);
            study_info.set("pat_id", info.get("pat_id"));
            study_info.set("study_iuid", info.get("study_iuid"));
            study_info.set("modality", info.get("modality"));
            study_info.set("hospital_code", hospitalCode);
            study_info.set("study_datetime", info.get("study_datetime"));
            study_info.set("createtime", DateUtil.getDateEN());
            study_info.set("study_desc", info.get("study_desc"));
            study_info.set("file_path", info.get("file_path"));
            study_info.set("kvp", info.get("kvp"));
            study_info.set("instituation", info.get("instituation"));
            study_info.set("study_device_id", info.get("study_device_id"));
            Db.save("pacs_study", study_info);

            re = Db.findFirst("select * from pacs_study where pat_id='" + info.get("pat_id") + "' and hospital_code='" + hospitalCode + "' and study_iuid='" + info.get("study_iuid") + "'");

            study_pk = re.get("pk") + "";

        }
        return study_pk;
    }

    public String saveSeries(Map<String, String> info, String study_pk) {
        String series_pk = null;
        Record re = Db.findFirst("select * from pacs_series where study_pk='" + study_pk + "' and series_iuid='" + info.get("series_iuid") + "'");
        if (re != null) {
            series_pk = re.get("pk") + "";

        } else {
            Record series_info = new Record();
            series_info.set("study_pk", study_pk);
            series_info.set("study_iuid", info.get("study_iuid"));
            series_info.set("series_iuid", info.get("series_iuid"));
            series_info.set("series_desc", info.get("series_desc"));
            series_info.set("width", info.get("width"));
            series_info.set("height", info.get("height"));
            series_info.set("createtime", DateUtil.getDateEN());
            series_info.set("pixs", info.get("pixs"));
            series_info.set("wc", info.get("wc"));
            series_info.set("ww", info.get("ww"));
            series_info.set("pn", info.get("pn"));

            Db.save("pacs_series", series_info);

            re = Db.findFirst("select * from pacs_series where study_pk='" + study_pk + "' and series_iuid='" + info.get("series_iuid") + "'");

            series_pk = re.get("pk") + "";

        }
        return series_pk;
    }

    public void saveSop(Map<String, String> info, String study_pk, String series_pk) {

        Record sop_info = new Record();
        sop_info.set("study_pk", study_pk);
        sop_info.set("series_pk", series_pk);
        sop_info.set("study_iuid", info.get("study_iuid"));
        sop_info.set("series_iuid", info.get("series_iuid"));
        sop_info.set("data1", info.get("data1"));
        sop_info.set("data2", info.get("index_num"));
        sop_info.set("sop_iuid", info.get("sop_iuid"));
        sop_info.set("dicom_path", info.get("dicom_path"));
        sop_info.set("createtime", DateUtil.getDateEN());

        Db.save("pacs_sop", sop_info);

    }

    public void createXml(Controller con, String port) {
        Record study_info = Db.findFirst("select * from pacs_study where pat_pk='" + con.getPara("pat_pk") + "' and study_iuid='" + con.getPara("study_iuid") + "'");

        if (study_info != null) {

            try {
                String basePath = study_info.getStr("file_path");
                List<Record> list = Db.find("select * from pacs_sop where study_pk=" + study_info.get("pk"));

                Element root = DocumentHelper.createElement("Images");
                Document document = DocumentHelper.createDocument(root);
                //给根节点添加属性
                root.addAttribute("Study", study_info.getStr("study_iuid")).addAttribute("Name", con.getPara("pat_name")).addAttribute("Port", port).addAttribute("Show", "Show");

                //给根节点添加孩子节点
                for (Record re : list) {
                    Element element1 = root.addElement("Item");
                    element1.addAttribute("sop", re.getStr("sop_iuid"));
                    element1.addText(re.getStr("dicom_path"));
                }

                //把生成的xml文档存放在硬盘上  true代表是否换行
                OutputFormat format = new OutputFormat("    ", true);
                format.setEncoding("UTF-8");//设置编码格式
                System.out.println(basePath + study_info.getStr("study_iuid") + ".xml");
                XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(basePath + study_info.getStr("study_iuid") + ".xml"), format);

                xmlWriter.write(document);
                xmlWriter.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    public int getPort() {

        int port = 10000;

        Record re = Db.findFirst("select * from port");
        if (re != null) {
            port = re.getInt("port");
            Db.update("update port set port=port+1 ");
        } else {
            Db.update("insert into port set port=10000");
        }
        return port;

    }

    public boolean saveVoice(String filePath, Controller con) {
        try {
            System.out.println(filePath);
            File fs = new File(filePath);

            BufferedInputStream bis = null;

            bis = new BufferedInputStream(con.getRequest().getInputStream());

            BufferedOutputStream bos = null;

            bos = new BufferedOutputStream(new FileOutputStream(fs));

            byte[] b = new byte[1024 * 64];
            int len = 0;
            try {
                while ((len = bis.read(b)) > 0) {
                    bos.write(b, 0, len);
                }
            } catch (IOException ex) {
                Logger.getLogger(PacsService.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                bos.flush();
            } catch (IOException ex) {
                Logger.getLogger(PacsService.class.getName()).log(Level.SEVERE, null, ex);
            }
            bos.close();
            return true;
        } catch (Exception ex) {
            return false;
        }
    }
}
